<!-- AvatarUpload.vue -->
<template>
  <el-dialog
    :modelValue="visible"
    @update:modelValue="$emit('update:visible', $event)"
    title="更新头像"
    width="400px"
    :close-on-click-modal="false"
  >
    <el-upload
      class="avatar-uploader"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :http-request="customUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar-preview" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
  </el-dialog>
</template>

<script setup>
import { ref, defineProps, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/UserStore'
import {downloadUserAvatarByUserId, uploadUserAvatarFile} from '@/api/User'

const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  avatarUrl: String
})

const emit = defineEmits(['update:visible', 'upload-success'])
const userStore = useUserStore()
const imageUrl = ref(props.avatarUrl || '')

const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}
// 将 Base64 字符串转换为 Blob，然后创建一个 URL 对象
function base64ToBlob(base64String) {
  const byteCharacters = atob(base64String);
  const byteNumbers = new Array(byteCharacters.length);
  for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
  }
  const byteArray = new Uint8Array(byteNumbers);
  return new Blob([byteArray], { type: 'image/png' });
}


const customUpload = async (options) => {
  try {
    const formData = new FormData()
    formData.append('file', options.file)
    console.log(options.file)
    const res = await uploadUserAvatarFile(userStore.userInfo.userId, formData)

    if (res.status === 'success') {
      const response = await downloadUserAvatarByUserId(userStore.userInfo.userId)
      // 将 Base64 字符串转换为 Blob
      const blob = base64ToBlob(response.data)
      emit('upload-success', URL.createObjectURL(blob))
      ElMessage.success('头像上传成功')

    } else {
      throw new Error(res.message || '上传失败')
    }
  } catch (error) {
    console.error('上传头像失败:', error)
    ElMessage.error(error.message || '上传失败')
  }
}
const handleClose = () => {
  emit('update:visible', false)
}
</script>

<style scoped>
.avatar-uploader {
  text-align: center;
}

.avatar-preview {
  width: 178px;
  height: 178px;
  border-radius: 6px;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>